import {Queue} from "../../utils/BuffUtils";
import EventUtils from "../../utils/EventUtils";
import {isString, stringToAscii} from "../../utils/CommonUtils"
import MessageConfig from "../../config/MessageConfig"
import LogService from "../LogService";


const APP_HEAD = [0xAA, 0x55];
const APP_TAIL = [0xBB, 0x44];

export const CMD_TYPE = {
  WriteWifiName: 0x01,
  ReadWifiName: 0x02,
  WriteWifiPassword: 0x03,
  ReadWifiPassword: 0x04,
  ConnectWifi: 0x05,
  WriteMqttUrl: 0x06,
  ReadMqttUrl: 0x07,
  WriteMqttPort: 0x08,
  ReadMqttPort: 0x09,
  WriteMqttId: 0x0A,
  ReadMqttId: 0x0B,
  WriteMqttUsername: 0x0C,
  ReadMqttUsername: 0x0D,
  WriteMqttPassword: 0x0E,
  ReadMqttPassword: 0x0F,
  NetworkConfigured: 0x10,
  ResetDevice: 0x11,
  GetBluMac: 0x13,
  WifiConnected: 0x12,
  ErrorDataLengthMismatch: 0x80
};

class LightPackage {
  queue = new Queue(200);
  step = 0;
  matchHeadIndex = 0;
  len = 0;
  body = {};
  deviceId = undefined;

  constructor(deviceId) {
    this.deviceId = deviceId;
  }

  clearBuf() {
    this.queue.clear();
  }

  decode(arr) {
    this.queue.addArr(arr);
    while (true) {
      switch (this.step) {
          // 匹配头
        case 0:
          if (this.matchHead()) {
            // LogService.debug("decode", "matchHead");
            this.step = 1;
          } else {
            return false;
          }
          break;
          // 长度
        case 1:
          //测试时打开
          // this.len = 18;
          // this.step = 2;
          //测试时关闭
          if (this.queue.getSize() > 0) {
            this.len = this.queue.getData();
            this.step = 2;
            // LogService.debug("decode", "len=" + this.len);
          } else {
            return false;
          }
          break;
          // 内容
        case 2:
          if (this.len > 255) {
            LogService.debug("decode", "len=" + this.len, "长度过程 无效数据包");
            this.step = 0;
          } else {
            // LogService.debug("decode", "len=" + this.len, "real size=" + this.queue.getSize());
            if (this.queue.getSize() >= this.len + 2) {
              this.step = 0;
              let contents = this.queue.getArr(this.len + 2);
              let size = contents.length;
              if (contents[size - 2] == APP_TAIL[0] && contents[size - 1] == APP_TAIL[1]) {
                this.decodeBody(contents);
                return true;
              } else {
                LogService.error(`错误的包结尾[${contents[size - 2]}, ${contents[size - 1]}]`);
              }
            } else {
              return false;
            }
          }
          break;
      }
    }
  }

  // 1, 255, 0, 0, 0, 0, 0, 0, 170, 1, 0, 1, 1, 0, 1, 100, 4
  //contents 13 B4 0E CF 12 44 D0
  decodeBody(contents) {
    this.body = {};
    this.body.type = contents[0];

    let index = 1;
    let v = 0;
    switch (this.body.type) {
      case CMD_TYPE.GetBluMac:
        let mac = '';
        for (let i = 1; i < contents.length-2; i++) {
          if(contents[i] > 15){
            mac += contents[i].toString(16).toUpperCase();
          }else{
            mac += "0" + contents[i].toString(16).toUpperCase();
          }

          if (i < contents.length-3){
            mac += ":";
          }
        }
        this.body.mac = mac;
        break;
    }
  }

  matchHead() {
    while (this.queue.getSize() > 0) {
      let data = this.queue.getData();
      if (APP_HEAD[this.matchHeadIndex] == data) {
        this.matchHeadIndex++;
      } else {
        this.matchHeadIndex = 0;
      }

      // LogService.debug("matchHead", "step", this.matchHeadIndex);
      if (this.matchHeadIndex == 2) {
        this.matchHeadIndex = 0;
        return true;
      }
    }
    return false;
  }
}

const packages = new Map();

EventUtils.on(MessageConfig.BlE_RECV_TYPE, (res) => {
  const {deviceId, data} = res;
  let arr = [];

  let devicePackage = packages.get(deviceId);
  if (!devicePackage) {
    devicePackage = new LightPackage();
    packages.set(deviceId, devicePackage);
  }
  devicePackage.deviceId = deviceId;

  console.log("lightPackage", devicePackage);

  let sucess = devicePackage.decode(data);
  if (sucess) {
    const {body} = devicePackage;
    EventUtils.trigger(MessageConfig.WIFI_CONFIG_RESPONSE, devicePackage);
    console.log("收到数据包:", deviceId, devicePackage);
  }
});

EventUtils.on(MessageConfig.BlE_CONNECT_TYPE, (res) => {
  const {deviceId, connected} = res;
  let lightPackage = packages.get(deviceId);
  if (!!lightPackage) {
    lightPackage.clearBuf();
  }
});

console.log("BluWifiConfigTp init");

export class PackageFactory {
  static addHeadTail(arr) {
    //测试时关闭
    arr.unshift(arr.length);

    arr.unshift(APP_HEAD[1]);
    arr.unshift(APP_HEAD[0]);

    arr.push(APP_TAIL[0]);
    arr.push(APP_TAIL[1]);
  }

  static getPackageArr(cmd, content) {

    let data;
    if (isString(content)) {
      data = stringToAscii(content);
    } else {
      data = content;
    }

    const arr = [];
    arr.push(cmd);
    if (!!data)
      arr.push(...data);
    PackageFactory.addHeadTail(arr);
    return arr;
  }
}

